<template>
  <div class="attribute-lay" v-loading="loading">
    <div class="attribute-content" v-if="hasData">
      <div class="attribute-item-lay">
        <div class="attribute-head">Key</div>
        <div class="attribute-head">Value</div>
      </div>
      <div v-for="(item, index) in attributes" :key="item.id">
        <div class="attribute-item-lay" v-show="canShow(item)">
          <div class="attribute-item">
            <el-input style="border: none;box-shadow: none" v-model="item.key" @input="checkKeyInput(item)"/>
          </div>
          <div class="attribute-item">
            <el-input style="border: none;box-shadow: none" v-model="item.value"/>
          </div>
          <div class="attribute-del" v-if="!props.readOnly">
            <el-popconfirm
                width="220"
                confirm-button-text="确定"
                cancel-button-text="取消"
                :icon="InfoFilled"
                icon-color="#626AEF"
                title="是否确定删除属性?"
                @confirm="deleteAttribute(item, index)"
            >
              <template #reference>
                <el-button style="padding: 0;width: 20px; height: 20px;" type="primary" round :icon="Minus"/>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </div>
      <div v-if="!props.readOnly">
        <el-button class="attribute-add" type="primary" :icon="Plus" plain text @click="addAttribute">
          添加属性
        </el-button>
      </div>
    </div>
    <div v-if="!hasData" style="display: flex; flex-direction: column; align-items: center; ">
      <div style="max-width: 680px" v-if="!props.readOnly">
        当前没有定义任何属性，请点击下方按钮添加属性，属性的Key和Value作为属性键值对必须填写。
      </div>
      <div style="max-width: 680px" v-if="props.readOnly">
        当前没有任何属性，请点击下方按钮再次刷新。
      </div>
      <div style="display: flex; flex-direction: row;">
        <el-button v-if="!props.readOnly" class="attribute-add" type="primary" :icon="Plus" plain text
                   @click="addAttribute">
          添加属性
        </el-button>
        <el-button class="attribute-add" plain :icon="Refresh" text @click="refresh">
          刷新
        </el-button>
      </div>
    </div>

    <div class="attribute-actions" v-if="hasData">
      <el-button v-if="!props.readOnly" type="primary" style="padding: 0 32px" @click="saveAttribute(false)">
        保存
      </el-button>
      <el-button v-if="!props.readOnly" type="primary" :icon="Back" text @click="restoreAttribute">
        恢复
      </el-button>
      <el-button plain :icon="Refresh" text @click="refreshAttribute">
        刷新
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">

import {nextTick, ref} from "vue";
import {Back, InfoFilled, Minus, Plus, Refresh} from "@element-plus/icons-vue";
import {removeAttributeOfAsset, loadAttributeOfAsset, saveAttributeOfAsset} from "@/apis";
import {useCurrent} from "@/utils/UseCurrentFunc";
import {msgError, msgInfo, msgWarn} from "@/utils/InfoUtil";
import {runMethod} from "@/utils/DateUtil";
import {SERVERS} from "@/stores/conf";
import {useStore} from "@/stores";

const store = useStore();
const hasData = ref();
const loading = ref(false);
const attributes: any = ref([]);

const props = withDefaults(defineProps<{
  entry: any,
  loadAttr?: any,
  saveAttr?: any,
  deleteAttr?: any,
  readOnly?: any,
  hideKeys?: any,
  targetId?: string,
}>(), {
  hideKeys: []
});

const {current} = useCurrent(props.entry.name);

const checkKeyInput = (item: any) => {
  item.key = item.key.replace(/[\W]/g,'');
}

const canShow = (item: any) => {
  return !item.key.startsWith('_') &&
      !item.key.startsWith('$') &&
      props.hideKeys.indexOf(item.key) == -1;
}

const getTargetId = () => {
  if (props.targetId) {
    return props.targetId;
  }
  if (SERVERS.REALM === props.entry.server) {
    return store.getCurrentRealms().id;
  } else {
    return store.getCurrentPlatform().id;
  }
}

const objectToAttribute = (objs: any, tag: string) => {
  Object.keys(objs).forEach(function (key) {
    attributes.value.push({
      key: key,
      value: objs[key],
      tag: tag,
    });
  });
  hasData.value = calcHasData();
}

const checkIsSave = () => {
  let ok: boolean = true;
  if (attributes.value && attributes.value.length !== 0) {
    for (let i = 0; i < attributes.value.length; ++i) {
      const item = attributes.value[i];
      if (!item.tag) {
        ok = false;
        break;
      }
    }
  }
  return ok;
}

const checkAttribute = () => {
  let ok: boolean = true;
  if (attributes.value && attributes.value.length !== 0) {
    for (let i = 0; i < attributes.value.length; ++i) {
      const item = attributes.value[i];
      if (!item.key || item.value == undefined) {
        ok = false;
        msgWarn('请输入Key和Value的值！');
        break;
      }
    }
  }

  return ok;
}

const attributeToObject = () => {
  let obj: any = {};
  if (attributes.value && attributes.value.length !== 0) {
    attributes.value.forEach((item: any) => {
      if (item.key && item.value != undefined && canShow(item)) {
        obj[item.key] = item.value;
      }
    })
  }
  return obj;
}

const restoreAttribute = () => {
  attributes.value = attributes.value.filter((item: any) => item.tag);
  // hasData.value = attributes.value.length !== 0;
}

const readAssetAttr = async (params: any) => {
  if (props.loadAttr) {
    return await props.loadAttr({
      server: props.entry.server,
      targetId: getTargetId(),
      ...params
    });
  } else {
    return await loadAttributeOfAsset({
      server: props.entry.server,
      targetId: getTargetId(),
      ...params
    });
  }
}

const deleteAssetAttr = async (params: any) => {
  if (props.deleteAttr) {
    return await props.deleteAttr(params);
  } else {
    return await removeAttributeOfAsset({
      server: props.entry.server,
      targetId: getTargetId(),
      ...params
    });
  }
}

const saveAssetAttr = async (params: any) => {
  if (props.saveAttr) {
    return await props.saveAttr({
      server: props.entry.server,
      targetId: getTargetId(),
      ...params
    });
  } else {
    return await saveAttributeOfAsset({
      server: props.entry.server,
      targetId: getTargetId(),
      ...params
    });
  }
}

const reloadAttr = async (setHasData: any) => {
  const result = await readAssetAttr({
    assetId: current().id,
    assetType: props.entry.type,
  });

  if (result && result.data && result.code === 0) {
    attributes.value = [];
    objectToAttribute(result.data, 'save');
  } else if (result) {
    if (setHasData) {
      hasData.value = false;
    }
    if (result.code !== 0) {
      msgError(result.message || '加载属性失败');
    }
  } else if (setHasData) {
    hasData.value = false;
  }
}

const doRefresh = async (setHasData: any) => {
  loading.value = true;
  await runMethod({}, async () => {
    await reloadAttr(setHasData);
  });
  loading.value = false;
}

const calcHasData = () => {
  if (attributes.value?.length == 0) {
    return false;
  } else {
    let count: number = 0;
    attributes.value?.forEach((item: any) => {
      if (canShow(item)) {
        count += 1;
      }
    })
    return count > 0;
  }
}

const refresh = async () => {
  if (hasData.value) {
    await doRefresh(true);
  } else {
    hasData.value = true;
    await nextTick(async () => await doRefresh(true));
  }
}

const refreshAttribute = async () => {
  if (!checkIsSave()) {
    msgWarn('当前存在未保存的属性！')
  } else {
    await doRefresh(false);
  }
}

const addAttribute = () => {
  attributes.value.push({key: '', value: ''});
  hasData.value = true;
}

const deleteAttribute = async (attr: any, index: number) => {
  if (attr.tag) {
    let data: any = [];
    data.push(attr.key);
    // 删除服务端
    const result = await deleteAssetAttr({
      assetId: current().id,
      assetType: props.entry.type,
      props: data,
    });
    if (!result || result.code !== 0) {
      msgError(result ? result.message : '删除属性失败');
      return;
    } else {
      attributes.value.splice(index, 1);
    }
  }

  // attributes.value.splice(index, 1);
  // hasData.value = attributes.value.length > 0;
}

const saveAttribute = async (setHasData: any) => {
  if (!checkAttribute()) {
    return;
  }
  const obj = attributeToObject();
  loading.value = true;
  await runMethod({}, async () => {
    const result = await saveAssetAttr({
      assetId: current().id,
      assetType: props.entry.type,
      props: {...obj},
    });
    if (result && result.code === 0) {
      await reloadAttr(setHasData);
      msgInfo('保存属性成功');
    } else if (result) {
      msgError(result.message);
    }
  });
  loading.value = false;
}

defineExpose({
  refresh,
})

</script>

<style scoped>
.attribute-lay {
  display: flex;
  flex-direction: column;
  color: #252A2F;
  padding: 8px 32px;
  flex: 1;
}

.attribute-content {
  display: flex;
  flex-direction: column;
}

.attribute-item-lay {
  display: flex;
  flex-direction: row;
  justify-content: stretch;
  align-items: center;
  width: 60%;
  min-width: 800px;
}

.attribute-head {
  font-weight: bold;
  flex: 1;
  margin: 8px 8px;
}

.attribute-item {
  flex: 1;
  margin: 8px 8px;
  border: 1px solid #f0f0f0;
  border-bottom: 1px solid #8a8d90;
}

.attribute-del {
  display: flex;
  margin: 8px;
  justify-content: center;
  align-items: center;
}


.attribute-item > .el-input__inner {
  border: 0;
  box-shadow: none;
}

.attribute-item > .el-textarea__inner {
  border: 0;
  resize: none;
}

.attribute-add {
  margin: 32px 0;
}

.attribute-actions {
  display: flex;
  flex-direction: row;
  margin: 8px 0 16px 8px;
}

:deep(.el-input__wrapper) {
  box-shadow: 0 0 0 0 var(--el-input-border-color, var(--el-border-color)) inset;
  cursor: default;
  border: none !important;
}

</style>
